﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using wUniAppPCL.IO;

namespace wUniAppPCL
{
  public interface IwStream
  {
    Stream GetStreamForRead();
    Stream GetStreamForWrite();
  }

  public class wFileStream : IwStream
  {
    public wFileStream(IwStorage wStorage, string fileName)
    {
      Storage = wStorage;
      FileName = fileName;
    }

    public IwStorage Storage { get; set; }
    public string FileName { get; set; }

    public Stream GetStreamForRead()
    {
      try
      {
        return Storage.OpenStream(FileName, true);
      }
      catch (Exception ex)
      {
        wLogger.ToLog(ex);
        return null;
      }
    }
    public Stream GetStreamForWrite()
    {
      return Storage.OpenStream(FileName, false);
    }
  }

  
  /// <summary>
  /// Neotestovane len pre ukazku do buducna na "cucania" dat z webu a nie suboru pred deserializaciou z JSONu
  /// </summary>
  public class wUriStream : IwStream
  {
    public wUriStream(Uri uri)
    {
      Uri = uri;
    }

    public Uri Uri { get; set; }
    public Stream GetStreamForRead()
    {
      AutoResetEvent autoResetEvent = new AutoResetEvent(false);
      IAsyncResult asyncResult = null;

      string url = Uri.AbsolutePath;
      var req = (HttpWebRequest)WebRequest.Create(url);

      req.BeginGetRequestStream(r => autoResetEvent.Set(), null);
      autoResetEvent.WaitOne();

      var res = req.EndGetRequestStream(asyncResult);

      return res;
    }

    public Stream GetStreamForWrite()
    {
      throw new NotImplementedException();
    }
  }
}
